package com.vdong.common.oauth.common.authorize.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 刀锋
 * @date : Create in 11:07 2018/6/27
 * @description:
 */
public class WebUtils {
    private static Logger logger = LoggerFactory.getLogger(WebUtils.class);
    static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 判断是否为包含json的ajax请求
     * @param request
     * @return
     */
    public static boolean isJsonRequest(HttpServletRequest request){
        String key = "json";
        String header = request.getHeader("Content-Type");
        if(!StringUtils.isEmpty(header) && header.toLowerCase().contains(key)){
            return true;
        }else {
            return false;
        }
    }

    public static void responseJson(HttpServletResponse response, Object o){
        try {
            response.setHeader("Content-Type", "application/json;charset=utf-8");
            response.getWriter().append(objectMapper.writeValueAsString(o));
            response.getWriter().flush();
        } catch (IOException e) {
            logger.error("发送json异常", e);
        }
    }
}
